package com.ikkong.platform.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.toolbox.Func;
import com.ikkong.core.toolbox.Record;
import com.ikkong.poor.model.*;
import com.ikkong.poor.service.PoorUsersService;
import com.ikkong.poor.service.impl.PoorUsersServiceImpl;
import com.ikkong.system.controller.base.UrlPermissController;
import com.ikkong.system.util.CommonUtil;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import org.beetl.sql.core.kit.StringKit;

import java.io.File;
import java.util.*;

/**
 * Generated by Blade.
 * 2016-10-08 15:59:45
 */
public class WebController extends UrlPermissController {
	private static String CODE = "blog";
	private static String PERFIX = "tb_tfw_blog";
	private static String LIST_SOURCE = "Blog.list";
	private static String BASE_PATH = "/platform/blog/";
    List<Place> placeCache = new ArrayList<>();
    List<Place> placeNameID = new ArrayList<>();
    static Map villageCache = new HashMap();
    List<String> idcartCache = new ArrayList<>();
	PoorUsersService service = new PoorUsersServiceImpl();


	private String placeIdToName(Integer groupId){
	    if(placeNameID.size()==0){
	        placeNameID = Blade.create(Place.class).findAll();
        }
        String res = "";
        for(Place pp:placeNameID){
            if(pp.getId() == groupId){
                res = pp.getName();
                break;
            }
        }
        return res;
    }

    private boolean isHasUser(String idcard){
        boolean b = false;
        if(idcartCache.size() == 0){
            List<String> select = Blade.dao().select("Blog.findIdcard", String.class);
            idcartCache = select;
        }
        if(StringKit.isNotBlank(idcard)){
            if(idcartCache.contains(idcard)){
                b = true;
            }else {
                idcartCache.add(idcard);
            }
        }
        return b;
    }

    private Map  placeToId(String xiang,String cun,String zu){
        boolean b = false;
        Integer id = 0;
        int x = 0;
        int c = 0;
        int z = 0;
        Blade blade = Blade.create(Place.class);
        if(placeCache.size() == 0){
            placeCache = blade.findAll();
        }
        if(StringKit.isNotBlank(xiang)){
            for(Place pp:placeCache){
                if(xiang.equals(pp.getName())){
                  x = pp.getId();
                    break;
                }
            }
            if(x == 0){//没有这个乡
                Place place = new Place();
                place.setIs_poor(1);
                place.setLevel("country");
                place.setName(xiang);
                place.setPid(1);
                int xiangID = blade.saveRtId(place);
                place.setId(xiangID);
                placeCache.add(place);
                x = xiangID;
            }
        }

        if(StringKit.isNotBlank(cun)){
            for(Place pp:placeCache){
                if(cun.equals(pp.getName())){
                    c = pp.getId();
                    break;
                }
            }
            if(c == 0){//没有这个村
                Place place = new Place();
                place.setIs_poor(1);
                place.setLevel("village");
                place.setName(cun);
                place.setPid(x);
                int cunID = blade.saveRtId(place);
                place.setId(cunID);
                placeCache.add(place);
                c = cunID;
            }
        }

        if(StringKit.isNotBlank(zu)){
            for(Place pp:placeCache){
                if(zu.equals(pp.getName())){
                    z = pp.getId();
                    break;
                }
            }
            if(z == 0){//没有这个村
                Place place = new Place();
                place.setIs_poor(1);
                place.setLevel("group");
                place.setName(zu);
                place.setPid(c);
                int zuID = blade.saveRtId(place);
                place.setId(zuID);
                placeCache.add(place);
                z = zuID;
            }
        }

        return Record.create().set("x",x).set("c",c).set("z",z);

    }

    private static void erroLog(String text){
        int text1 = Blade.dao().update("Blog.tmp", Record.create().set("text", text));

    }

    public void index(){
        List<Map> select = Blade.dao().select("Blog.findCountry", Map.class);
        Object info = Blade.create(IndexInfo.class).findById(1);
        setAttr("info",info);
        setAttr("country",select);
        render("/ganluo.html");
    }

    public void updateData(){
        Integer allcun = Blade.dao().selectSingle("Blog.allCuns", null, Integer.class);
        Map map = Blade.dao().selectSingle("Blog.allFamily", null, Map.class);
        IndexInfo indexInfo = Blade.create(IndexInfo.class).findById(1);
        indexInfo.setCun_num(allcun);
        indexInfo.setPoor_family_num(Func.toInt(map.get("family")));
        indexInfo.setPoor_people_num(Func.toInt(map.get("users")));
        boolean update1 = Blade.create(IndexInfo.class).update(indexInfo);

        List<Map> select = Blade.dao().select("Blog.cunsCount", Map.class);
        for(Map mm:select){
            if(mm!=null){
                Object id = mm.get("pid");
                Object num = mm.get("num");
                int update = Blade.dao().update("Blog.updatePlace", Record.create().set("id", id).set("num", num));
            }
        }
        renderJson(success("更新成功"));
    }


    private static List getVillageCount(String id){
        if(villageCache==null || villageCache.get("lasttime") == null){
            List<Map> cuns = Blade.dao().select("Blog.findCun", Map.class,Record.create().set("pid",id));
            villageCache.put("lasttime",new Date().getTime());
            villageCache.put(id,cuns);
        }else if(new Date().getTime() - Func.toLong(villageCache.get("lasttime")) >  10000L){
            List<Map> cuns = Blade.dao().select("Blog.findCun", Map.class,Record.create().set("pid",id));
            villageCache.put("lasttime",new Date().getTime());
            villageCache.put(id,cuns);
        }else if(villageCache.get(id)==null){
            List<Map> cuns = Blade.dao().select("Blog.findCun", Map.class,Record.create().set("pid",id));
            villageCache.put("lasttime",new Date().getTime());
            villageCache.put(id,cuns);
        }

        return (List)villageCache.get(id);
    }


    //乡村统计信息
    public void initCount(){
        long time1 = new Date().getTime();
        List<Map> select = Blade.dao().select("Blog.findCountry", Map.class);
        Blade blade = Blade.create(Place.class);
        int succ = 0;

        for(Map mm:select){
            if(mm!=null){
                Object id = mm.get("id");
                if(id==null){
                    continue;
                }
                int countryNum = 0;
                int countryUser = 0;
                List<Map> cuns = getVillageCount(id.toString());
                for(Map cc:cuns){
                    int vill = Func.toInt(cc.get("id"));
                    int family = Func.toInt(cc.get("family"));
                    int family_num = Func.toInt(cc.get("users"));
                    countryNum += family;
                    countryUser+=family_num;
                    int update = Blade.dao().update("Blog.updatePlace", Record.create().set("family", family).set("users", family_num).set("id", vill));
                    succ++;
                }
                int update = Blade.dao().update("Blog.updatePlace", Record.create().set("family", countryNum).set("users", countryUser).set("id", id));
                succ++;
            }
        }
        long time2 = new Date().getTime();
        long l = time2 - time1;
        System.out.println("time============" + l);
        renderJson(succ);
    }

    public void village(){
        String type = getPara("type");

        String name = getPara("name");
        String id = getPara("id");
        //获取乡镇菜单
        List<Map> select = Blade.dao().select("Blog.findCountry", Map.class);
        //获取村级菜单
        List<Map> cuns ;
        Integer page = getParaToInt("page", 1);
        Integer rows = getParaToInt("rows", 10);
        int start = (page - 1) * rows;


        Map para = new HashMap();
        Place place = Blade.create(Place.class).findById(id);
        if(StringKit.isNotBlank(name)){
            para.put("name","%"+name + "%");
        }
        para.put("start",start);
        para.put("rows",rows);
        if("village".equals(type)){
            setAttr("type","village");
            para.put("village",id);
          cuns  = Blade.dao().select("Blog.findMenuCun", Map.class,Record.create().set("pid",place.getPid()));
        }else {
           cuns = Blade.dao().select("Blog.findMenuCun", Map.class,Record.create().set("pid",id));
            setAttr("type","country");
            para.put("country",id);
        }

        Integer family = place.getFamily();

        //获取贫困户信息
        List<Map> users = Blade.dao().select("Blog.userList", Map.class, para);
        for(Map mm:users){
            if(mm!=null){
                mm.put("xian",placeIdToName(Func.toInt(mm.get("xian"))));
                mm.put("country",placeIdToName(Func.toInt(mm.get("country"))));
                mm.put("village",placeIdToName(Func.toInt(mm.get("village"))));
                mm.put("group",placeIdToName(Func.toInt(mm.get("group"))));
            }
        }
        if(family % 10==0){
            setAttr("all_page",family/10);
        }else {
            setAttr("all_page",(family/10) + 1);
        }
        setAttr("users",users);
        setAttr("page",page);
        setAttr("id",id);
        setAttr("pid",place.getPid());
        setAttr("name",name);
        setAttr("records",family);
        setAttr("cuns",cuns);
        setAttr("country",select);
        long time2 = new Date().getTime();
        render("/village.html");
    }

    public void detailCode(){
        String basePath = PropKit.get("wwwpath");
        String id = getPara("id");
        String url = basePath + "/ganluo/detail?id="+id;
        renderQrCode(url,120,120);
    }
    public void detail(){
        String familyId = getPara("id");
        List<PoorUsers> family = Blade.create(PoorUsers.class).findBy("family = " + familyId + " order by is_host desc", PoorUsers.class);
        PoorUsers host = new PoorUsers();
        if(family.size()>0){
            host = family.get(0);
        }

//        List<Map> family = Blade.dao().select("Blog.familyUser", Map.class, Record.create().set("family", familyId));
        List<OutOnline> oo = Blade.create(OutOnline.class).findBy(" family_id = " + familyId, OutOnline.class);
        List<OutShehui> os = Blade.create(OutShehui.class).findBy(" family_id = " + familyId, OutShehui.class);
        setAttr("oo",oo);
        setAttr("os",os);
        setAttr("family",family);
        setAttr("host",host);
        setAttr("xiang",placeIdToName(host.getCountry()));
        setAttr("cun",placeIdToName(host.getVillage()));
        setAttr("zu",placeIdToName(host.getGroup()));
        setAttr("old",CommonUtil.IdNOToAge(host.getIdcard()));

        render("/detail.html");
    }

//    public void  importUsers(){
//        ImportParams params = new ImportParams();
//        params.setTitleRows(1);
//        params.setHeadRows(1);
//        int succ = 0;
//        int fail = 0;
//        int chongfu = 0;
//        List<PoorUsers_tmp> list = ExcelImportUtil.importExcel(
//                new File("D:\\poor_test.xlsx"),
//                PoorUsers_tmp.class, params);
//        for(PoorUsers_tmp pu:list){
//            PoorUsers user = new PoorUsers();
//            String idcard = pu.getIdcard();
//            boolean hasUser = isHasUser(idcard);
//            if(hasUser == true){
//                erroLog(idcard + "重复");
//                chongfu++;
//                continue;
//            }
//            user.setXian(1);
//            String country = pu.getCountry();
//            String village = pu.getVillage();
//            String group = pu.getGroup();
//            Map map = placeToId(country, village, group);
//            if(map == null){
//                fail++;
//                erroLog(idcard);
//                continue;
//            }
//            user.setCountry(Func.toInt(map.get("x")));
//            user.setVillage(Func.toInt(map.get("c")));
//            user.setGroup(Func.toInt(map.get("z")));
//            user.setFamily(pu.getFamily());
//            user.setUser_num(pu.getUser_num());
//            user.setName(pu.getName());
//            user.setIdcard(pu.getIdcard());
//            user.setFamily_mans(pu.getFamily_mans());
//            user.setRalation(pu.getRalation());
//            user.setNation(pu.getNation());
//            user.setEducation(pu.getEducation());
//            user.setEdu_detail(pu.getEdu_detail());
//            user.setHealth(pu.getHealth());
//            user.setWorker(pu.getWorker());
//            user.setJob_detail(pu.getJob_detail());
//            user.setJob_month(pu.getJob_month());
//            user.setJoin_dabinyiliao(pu.getJoin_dabinyiliao());
//            user.setTuopin_type(pu.getTuopin_type());
//            user.setTuopin_year(pu.getTuopin_year());
//            user.setPoor_reason(pu.getPoor_reason());
//            user.setIs_dangerHourse(pu.getIs_dangerHourse());
//            user.setIs_safeWater(pu.getIs_safeWater());
//            user.setPer_income(pu.getPer_income());
//            user.setTel(pu.getTel());
//            user.setRegist_year(pu.getRegist_year());
//            user.setRenyuan_regist_year(pu.getRenyuan_regist_year());
//            if(pu.getRalation()!=null){
//                if(pu.getRalation().equals("户主")){
//                    user.setIs_host(1);
//                }else {
//                    user.setIs_host(0);
//                }
//            }
//            boolean save = service.save(user);
//            if(save){
//                succ++;
//            }else {
//                fail++;
//                erroLog(idcard);
//                continue;
//            }
//        }
//        renderJson(json(Record.create().set("succNum",succ).set("fail",fail).set("chongfu",chongfu)));
//    }



    public void  importSales(){
		ImportParams params = new ImportParams();
		params.setTitleRows(0);
		params.setHeadRows(1);
        int succ1 = 0;
        int succ2 = 0;
        int fail = 0;
        int chongfu = 0;
		List<PoorSales_tmp> list = ExcelImportUtil.importExcel(
				new File("D:\\out.xls"),
                PoorSales_tmp.class, params);
        Blade outOnline = Blade.create(OutOnline.class);
        Blade outShehui = Blade.create(OutShehui.class);
        for(PoorSales_tmp pu:list){
            String family_id = pu.getFamily_id();
            if(family_id==null){
                continue;
            }
           OutOnline oo = new OutOnline();
            oo.setFamily_id(family_id);
            oo.setMoney(pu.getMoney());
            oo.setMoney_online(pu.getMoney_online());
            oo.setPlan_num(pu.getPlan_num());
            oo.setProduct(pu.getProduct());
            oo.setSale_num(pu.getSale_num());
            boolean save = outOnline.save(oo);
            if(save){
                succ1++;
            }else {
                fail++;
            }
            OutShehui os = new OutShehui();
            os.setFamily_id(pu.getFamily_id());
            os.setBuys(pu.getBuys());
            os.setMoney_shehui(pu.getMoney_shehui());
            os.setOrganize(pu.getOrganize());
            os.setWuzi(pu.getWuzi());
            os.setXianjin(pu.getXianjin());
            boolean save1 = outShehui.save(os);
            if(save1){
                succ2++;
            }else {
                fail++;
            }

        }
        renderJson(json(Record.create().set("电商成功",succ1).set("社会扶贫成功",succ2).set("fail",fail).set("chongfu",chongfu)));
	}


}
